package com.lemon.smartsafetynew.ui.fragment.work;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.ApplicationInfo;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.data.app.DataUtil;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.main.MainPanelButton;
import com.lemon.smartsafety.entity.main.MainRcvItemBase;
import com.lemon.smartsafety.http.UrlInfo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.ui.adapter.common.RcvViewType;
import com.lemon.smartsafetynew.entity.message.MessageBo;
import com.lemon.smartsafetynew.net.services.PushMessageServices;
import com.lemon.smartsafetynew.ui.activity.hidden.SafeHiddenDangerHomeNewActivity;
import com.lemon.smartsafetynew.ui.activity.message.MessageListActivity;
import com.lemon.smartsafetynew.ui.activity.task.InspectionTaskActivity;
import com.lemon.smartsafetynew.ui.fragment.base.ToolbarBasePullToRefreshNoLoadMoreFragment;
import com.lemon.smartsafety.update.UpdateManager;
import com.lemon.smartsafety.utils.GsonUtil;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.common.AndroidUpdateInfo;
import com.lemon.smartsafetynew.entity.common.CommonBo;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.entity.event.common.UserInfoRefreshEvent;
import com.lemon.smartsafetynew.entity.event.work.WorkUIEvent;
import com.lemon.smartsafetynew.entity.ledger.LedgerBuildingItemVo;
import com.lemon.smartsafetynew.entity.ledger.LedgerRadarVo;
import com.lemon.smartsafetynew.entity.me.MeCompanyVo;
import com.lemon.smartsafetynew.entity.work.OverViewVo;
import com.lemon.smartsafetynew.net.services.CommonServices;
import com.lemon.smartsafetynew.net.services.SafeLedgerServices;
import com.lemon.smartsafetynew.ui.activity.device.DeviceHomeActivity;
import com.lemon.smartsafetynew.ui.activity.electrical.ElectricalSafeHomeActivity;
import com.lemon.smartsafetynew.ui.activity.electrical.ElectricalSafePointListActivity;
import com.lemon.smartsafetynew.ui.activity.hidden.SafeHiddenDangerHomeActivity;
import com.lemon.smartsafetynew.ui.activity.hidden.SafeHiddenSnapshotActivity;
import com.lemon.smartsafetynew.ui.activity.incident.IncidentHomeActivity;
import com.lemon.smartsafetynew.ui.activity.ledger.LedgerBuildingCheckItemListActivity;
import com.lemon.smartsafetynew.ui.activity.monitor.MonitorHomeActivity;
import com.lemon.smartsafetynew.ui.activity.monitor.MonitorVideoActivity;
import com.lemon.smartsafetynew.ui.activity.monitor.MonitorVideoHomeActivity;
import com.lemon.smartsafetynew.ui.activity.patrol.SafePatrolHomeActivity;
import com.lemon.smartsafetynew.ui.activity.record.RecordFunctionActivity;
import com.lemon.smartsafetynew.ui.activity.record.RecordHomeActivity;
import com.lemon.smartsafetynew.ui.activity.training.OnlineTrainingActivity;
import com.lemon.smartsafetynew.ui.adapter.work.WorkFragmentAdapter;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.common.NotificationsUtils;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.lemon.smartsafetynew.util.user.UserTypeUtil;
import com.lemon.smartsafetynew.web.HtmlActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import kale.adapter.LemonRcvAdapter;

/**
 * Created by Andrew on 2017/7/3.
 */

/**
 * [工作]页面的布局和逻辑
 */
public class WorkFragment extends ToolbarBasePullToRefreshNoLoadMoreFragment<MainRcvItemBase, List<MainRcvItemBase>> {

    private Context mContext;

    public Gson mGson;

    //private List<MainPanelButton> mMainButtons;
    //private List<MainPanelButton> mSecondaryButtons;

    private User user;

    private boolean viewFinish = false;

    private boolean first_time = true;

    private Menu mMenu;

    @Override
    public void onPullRefresh() {
        getHomePageInfo();
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public boolean goRefreshOnCreate() {
        return false;
    }

    @Override
    public LemonRcvAdapter<MainRcvItemBase> getLemonAdapter() {
        return new WorkFragmentAdapter(mDataList);
    }

    @Override
    public String getHttpTag() {
        //不使用BasePullToRefreshNoLoadMoreFragment中的Event回到处理
        return "";
    }

    @Override
    protected int getTitle() {
        return R.string.app_name;
    }

    @Override
    protected void initViews() {
        super.initViews();
        viewFinish = false;
        mContext = getActivity();
        mGson = GsonUtil.getCommonGson();

        // ========== 初始化RecyclerView ==========
        initData();

        // ========== 刷新页面数据 ==========
        mPullToRefreshRecyclerView.beginRefreshing();

        // ====== 检测并提示 用户打开接收通知栏消息 ============
        if (!NotificationsUtils.isNotificationEnabled(getmContext())) {
            showNotificationDialog("为了确保您能接收到系统发出的所有消息通知，请开启应用接收通知的功能。");
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        getPushListStatus(); //推送的读取状态
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        viewFinish = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelDialog();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        mMenu = menu;
        inflater.inflate(R.menu.menu_message, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        switch (id) {
            case R.id.action_message:
                UIHelper.showActivity(getmContext(), MessageListActivity.class);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void initData() {

        mDataList.clear();

        List<MainPanelButton> mMainButtons = DataUtil.getWorkMainUIButtons();
        List<MainPanelButton> mSecondaryButtons = DataUtil.getWorkSecondaryUIButtons();

        rightOne.setVisibility(View.GONE);
        rightTwo.setVisibility(View.GONE);

        //Banner
        OverViewVo overViewVo = new OverViewVo();
        MainRcvItemBase<OverViewVo> banner = new MainRcvItemBase<>();
        banner.setViewType(RcvViewType.MainRcvViewType.TYPE_BANNER);
        banner.setData(overViewVo);
        mDataList.add(banner);

        //添加空白的占位行
        MainRcvItemBase head1 = new MainRcvItemBase();
        head1.setViewType(RcvViewType.MainRcvViewType.TYPE_SECTION_HEAD);
        mDataList.add(head1);

        //工作页面 主要的操作选项
        MainRcvItemBase<List<MainPanelButton>> mainItemOption = new MainRcvItemBase<>();
        mainItemOption.setViewType(RcvViewType.MainRcvViewType.TYPE_MAIN_OPTION);
        mainItemOption.setData(mMainButtons);
        mDataList.add(mainItemOption);

        //添加空白的占位行
        mDataList.add(head1);

        //工作页面 次级操作选项
        MainRcvItemBase<List<MainPanelButton>> secondaryItemOption = new MainRcvItemBase<>();
        secondaryItemOption.setViewType(RcvViewType.MainRcvViewType.TYPE_SECONDARY_OPTION);
        secondaryItemOption.setData(mSecondaryButtons);
        mDataList.add(secondaryItemOption);

        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }

    }


    /**
     * 点击事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(WorkUIEvent event) {

        // ======== 获取用户信息 ======
        User userInfo = AccountUtil.getUser();
        if (userInfo == null) {
            // ===== 用户信息为空时，重新登陆 =====
            UIHelper.showLoginActivityNew(mContext);
            return;
        }

        MainPanelButton panelButton = event.getMainPanelButton();

        if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.COMPANY_INFO) {
            //一企一档
            if (!UserTypeUtil.isGovType(AccountUtil.getUserType())) { //非政府人员使用模块
                MeCompanyVo companyVo = new MeCompanyVo();
                companyVo.setCompany_code(AccountUtil.getCompanyCode());
                companyVo.setCompany_id(AccountUtil.getCompanyId());
                companyVo.setCompany_name(AccountUtil.getCompanyName());
                Bundle bundle = new Bundle();
                bundle.putSerializable(KeyConstants.KEY_COMPANY_VO, companyVo);
                UIHelper.showActivity(mContext, bundle, RecordFunctionActivity.class);
            } else {
                UIHelper.showActivity(mContext, RecordHomeActivity.class);
            }
        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.SAFE_HIDDEN_DANGER) {
            //安全隐患
            UIHelper.showActivity(mContext, SafeHiddenDangerHomeNewActivity.class);
        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.SAFE_LEDGER) {
            //点位台账
            LedgerBuildingItemVo data = new LedgerBuildingItemVo();
            data.setBuilding_id(AccountUtil.getCompanyId());

            Bundle bundle = new Bundle();
            bundle.putSerializable(KeyConstants.KEY_LEDGER_PATROL_BUILDING_VO, data);
            UIHelper.showActivity(mContext, bundle, LedgerBuildingCheckItemListActivity.class);
            //UIHelper.showActivity(mContext, LedgerHomeActivity.class);

        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.MONITOR) {
            //实时监控
            UIHelper.showActivity(mContext, MonitorHomeActivity.class);

        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.DEVICE_MANAGE) {
            //设备管理
            UIHelper.showActivity(mContext, DeviceHomeActivity.class);

        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.EVENT_PROCESS) {
            //事件管理
            UIHelper.showActivity(getmContext(), IncidentHomeActivity.class);

        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.LAWS_REGULATIONS) {
            //法律法规
            mHUDUtil.showDoneTip("将来会有的呢");
        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.CASE_SHARE) {
            //案件分享
            mHUDUtil.showDoneTip("现在还木有呢");
        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.KNOWLEDGE_BASE) {
            //知识库
            mHUDUtil.showDoneTip("我们会努力实现的呢");
        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.ONLINE_CLASAROOM) {
            //在线课堂
            UIHelper.showActivity(getmContext(), OnlineTrainingActivity.class);

        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.SNAPSHOT) {
            //网格员随手拍
            UIHelper.showActivity(getmContext(), SafeHiddenSnapshotActivity.class);
        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.ELECTRICAL_SAFETY) {
            //用电安全  暂时不在首页展示了
            if (!UserTypeUtil.isGovType(AccountUtil.getUserType())) { //非政府人员使用模块
                UIHelper.showActivity(getmContext(), ElectricalSafePointListActivity.class);
            } else {
                UIHelper.showActivity(getmContext(), ElectricalSafeHomeActivity.class);
            }

        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.VIDEO_MONITOR) {
            //视频监控  暂时不在首页展示了
            if (!UserTypeUtil.isGovType(AccountUtil.getUserType())) { //非政府人员使用模块
                UIHelper.showActivity(getmContext(), MonitorVideoActivity.class);
            } else {
                UIHelper.showActivity(getmContext(), MonitorVideoHomeActivity.class);
            }
        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.PATROL_PATH) {
            //任务路线
            UIHelper.showActivity(mContext, SafePatrolHomeActivity.class);
        } else if (panelButton.getWorkOptionCode() == ApplicationInfo.WorkOptionCodeEnum.INSPECTION_TASK) {
            //巡查任务
            UIHelper.showActivity(mContext, InspectionTaskActivity.class);
        }
    }

    // ====== 当用户信息刷新成功后，本地更新一次主页 =======
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserInfoRefreshSuccess(UserInfoRefreshEvent event) {
        //initData();
        //TODO
    }

    /**
     * 获取首页信息
     */
    private void getHomePageInfo() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("date", CommonUtil.getNowTimeStr(DateTypeEnum.MONTH));

        SafeLedgerServices
                .init()
                .getHomePageInfo(params);
    }

    /**
     * 获取通知消息
     */
    private void getPushListStatus() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("user_id", AccountUtil.getUserID());

        PushMessageServices
                .init()
                .getNoticeStatus(params);
    }

    /**
     * 升级用的地方，获取服务器的版本信息
     */
    public void getVersionInfo() {
        LemonRequestParams params = new LemonRequestParams("");
        params.put("version_code", AppUtils.getVersionCode(IApplication.context()));
        CommonServices.init().updateAppVersion(params);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        try {

            if (KeyConstants.URL_APP_UPDATE_VERSION.equals(event.getTag())) {                //版本更新部分逻辑
                if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                    if (event.getEventResult() == Constants.Result.SUCCESS) {
                        if (event.getObj() instanceof AndroidUpdateInfo) {
                            AndroidUpdateInfo item = (AndroidUpdateInfo) event.getObj();
                            if (null != item) {
                                boolean isForce = CommonBo.Status.status_true.getValue().equals(item.getIs_force());
                                UpdateManager updateManager = new UpdateManager(item.getVersion_remark(), item.getDownload_url(), item
                                        .getVersion_name(), Constants.APP_DOWNLOAD_FILE_NAME, isForce, getActivity());
                                updateManager.checkUpdateInfo();
                            }
                        }
                    } else {
                        //mHUDUtil.showErrorTip(event.getMsg());
                    }
                }
            } else if (KeyConstants.URL_GET_HOME_PAGE_INFO.equals(event.getTag())) {                 //获取首页信息
                // 获取首页信息状态，更新列表
                mPullToRefreshRecyclerView.onRefreshComplete();

                if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                    if (Constants.Result.SUCCESS == event.getEventResult()) {

                        if (event.getObj() instanceof OverViewVo) { //TODO  wait API

                            //Banner
                            MainRcvItemBase<OverViewVo> banner = new MainRcvItemBase<>();
                            banner.setViewType(RcvViewType.MainRcvViewType.TYPE_BANNER);
                            banner.setData((OverViewVo) event.getObj());
                            mDataList.set(0, banner);

                            //工作页面 主要的操作选项
                            List<MainPanelButton> mMainButtons = DataUtil.getWorkMainUIButtons();
                            MainRcvItemBase<List<MainPanelButton>> mainItemOption = new MainRcvItemBase<>();
                            mainItemOption.setViewType(RcvViewType.MainRcvViewType.TYPE_MAIN_OPTION);
                            mainItemOption.setData(mMainButtons);
                            mDataList.set(2, mainItemOption);

                            if (mAdapter != null) {
                                mAdapter.notifyDataSetChanged();
                            }

                            if (first_time) {
                                first_time = false;
                                getVersionInfo(); //检查升级
                            }

                            getPushListStatus(); //推送的读取状态

                        }


                    } else if (Constants.Result.ERROR == event.getEventResult()) {
                        mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                            @Override
                            public void onCall() {

                            }
                        });
                    }
                }
            } else if (KeyConstants.URL_PUSH_MESSAGE_STATUS.equals(event.getTag())) {                //推送状态
                if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                    if (event.getEventResult() == Constants.Result.SUCCESS) {

                        String status = (String) event.getObj();
                        if (MessageBo.MessageStatus.normal.getValue().equals(status)) {
                            mMenu.getItem(0).setIcon(R.mipmap.icon_message_empty);
                        } else {
                            mMenu.getItem(0).setIcon(R.mipmap.icon_message_not_empty);
                        }

                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 在线课堂
     */
    private void onlineClassroom() {

        SharedPreferencesServer mSharedPreferencesServer = new SharedPreferencesServer(getmContext());
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.ONLINE_CLASSROOM, Constants.GSAFE);
        Bundle bundle = new Bundle();
        bundle.putString(KeyConstants.KEY_HTML_URL, serverUrl);
        bundle.putInt(KeyConstants.KEY_TITLE_ID, R.string.work_options_secondary_4);
        UIHelper.showActivity(getmContext(), bundle, HtmlActivity.class);
    }

    /**
     * dialog
     */
    private MaterialDialog chooseDialog;
    private MaterialDialog notificationTipsDialog;

    private void showChooseDialog(String remark) {
        chooseDialog = new MaterialDialog.Builder(getmContext())
                .title("提示")
                .content(remark)
                .negativeText("继续")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        onlineClassroom();
                    }
                })
                .positiveText("取消")
                .show();
    }

    private void showNotificationDialog(String remark) {
        notificationTipsDialog = new MaterialDialog.Builder(getmContext())
                .title("提示")
                .content(remark)
                .negativeText("设置")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        enableNotification();
                    }
                })
                .positiveText("下一次")
                .show();
    }

    private void cancelDialog() {

        if (chooseDialog != null && chooseDialog.isShowing()) {
            chooseDialog.dismiss();
            chooseDialog = null;
        }

        if (notificationTipsDialog != null && notificationTipsDialog.isShowing()) {
            notificationTipsDialog.dismiss();
            notificationTipsDialog = null;
        }
    }


    /**
     * 跳转设置开启通知页面
     */
    private void enableNotification() {
        try {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Intent intent = new Intent();
                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                intent.putExtra("app_package", getActivity().getPackageName());
                intent.putExtra("app_uid", getActivity().getApplicationInfo().uid);
                startActivity(intent);
            } else if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
                startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
